import axios, { AxiosInstance, AxiosResponse, AxiosError } from 'axios';
import router from "../router";
import { ElMessage } from 'element-plus';

// 响应数据接口
interface ApiResponse<T = any> {
    code: number
    message: string
    data?: T
}

// 用户信息接口
interface UserInfo {
    token: string
    [key: string]: any
}

// 用户登录接口
interface UserLogin {
    username?: string
    email?: string
    password?: string
    passwordHash?: string
    [key: string]: any
}

// 订单接口
interface Orders {
    id?: number
    userId?: number
    orderNumber?: string
    totalAmount?: number
    status?: string
    paymentMethod?: string
    shippingAddress?: string
    productsItems?: {
        productId?: number
        quantity?: number
        specId?: number
        [key: string]: any
    }
    [key: string]: any
}

// 添加Products接口定义
interface Products {
    productId?: number;
    storeId?: number;
    categoryId?: number;
    name?: string;
    description?: string;
    price?: number;
    salePrice?: number;
    stock?: number;
    mainImage?: string;
    rating?: number;
    reviewCount?: number;
    salesCount?: number;
    isFeatured?: number;
    isNew?: number;
    createdAt?: string;
    cartItemId?: string;
    quantity?: number;
    storeName?: string;
    selected?: number;
    specValue?: string;
    isAmple?: number;
}

// 声明全局APP_CONFIG类型
declare global {
    interface Window {
        APP_CONFIG: {
            apiBaseUrl: string;
            [key: string]: any;
        }
    }
}

// 枚举管理注册模块接口地址
enum API {
    // 注册接口地址
    REGISTER = '/user/register',
    GET_CODE = '/auth',
    LOGIN = '/user/login',
    FIND_PASSWORD = '/user/changePasswordByEmail',
}

// 注册相关函数
export const goRegister = (user: UserLogin) => {
    // 直接传递 user 对象
    return request.post(API.REGISTER, user)
}

export const getCode = (email: string) => {
    console.log('发送验证码请求，邮箱:', email); // 添加调试日志
    return request
        .post(`/email/send-code?email=${encodeURIComponent(email)}`) // 使用查询参数
        .then((response) => {
            console.log('验证码发送成功，响应:', response); // 添加调试日志
            return response.data;
        })
        .catch((error) => {
            console.error('获取验证码失败:', error) // 添加调试日志
            throw error // 抛出错误以便调用者处理
        })
}

export const verifyCode = (email: string, code: string) => {
    return request
        .post(`/email/verify-code?email=${encodeURIComponent(email)}&code=${encodeURIComponent(code)}`) // 使用查询参数
        .then((response) => {
            console.log('验证码验证成功，响应:', response); // 添加调试日志
            return response.data;
        })
        .catch((error) => {
            console.error('校验验证码失败:', error)
            throw error // 抛出错误以便调用者处理
        })
}

export const goLogin = (email: string, password: string) => {
    return request.post(API.LOGIN, { email, password })
}

export const findPassword = (email: string, password: string) => {
    return request.post(API.FIND_PASSWORD, { email, password })
}

// API基础URL (这个对象包含了我们需要的信息)
const backendAPI = {
    baseUrl: window.APP_CONFIG?.apiBaseUrl || 'http://localhost:8081'
};

// 创建不同的axios实例
let instance: AxiosInstance = axios.create({ baseURL: backendAPI.baseUrl });
let withToken: AxiosInstance = axios.create({ baseURL: backendAPI.baseUrl });
let withTokenNoIntercept: AxiosInstance = axios.create({ baseURL: backendAPI.baseUrl });

// 创建request实例用于注册相关API
const request = axios.create({ baseURL: backendAPI.baseUrl });

// 通用响应处理
let commonResponse = function (res: AxiosResponse<ApiResponse>): Promise<AxiosResponse<ApiResponse>> {
    if (res.data.code === 100) {
        return Promise.resolve(res);
    } else {
        console.error("请求错误，服务器返回错误信息：" + res.data.message);
        return Promise.reject(res.data.message);
    }
}

// 通用错误处理
let commonErr = function (err: AxiosError): Promise<never> {
    console.log(err);
    console.error("请求发生错误：" + err);
    return Promise.reject(err);
}

// 无token实例拦截器
instance.interceptors.response.use(commonResponse, commonErr);

// 带token实例请求拦截器
withToken.interceptors.request.use(
    (config: any) => {
        if (localStorage.user_info) {
            try {
                const userInfo: UserInfo = JSON.parse(localStorage.user_info);
                // 优先使用token字段，如果没有则使用passwordHash字段
                const token = userInfo.token || userInfo.passwordHash;
                if (token && typeof token === 'string') {
                    config.headers["Authorization"] = token;
                }
            } catch (error) {
                console.error('解析用户信息失败:', error);
                localStorage.removeItem('user_info');
            }
        }
        return config;
    },
    (err: any) => {
        console.error('请求超时');
        return Promise.reject(err);
    }
);

// 带token实例响应拦截器
withToken.interceptors.response.use(
    (res: any) => {
        if (res.data.code === 100) {
            return res.data;
        } else if (res.data.code === 102) {
            localStorage.removeItem('user_info');
            ElMessage.error("登录已过期，请重新登录");
            router.push('/login');
            return Promise.reject(res.data.message);
        } else if (res.data.code === 103) {
            console.error("密码错误，请重新输入");
            return Promise.reject(res.data.message);
        } else {
            ElMessage.error("请求错误，服务器返回：" + res.data.message);
            console.error("请求错误，服务器返回：" + res.data.message);
            return Promise.reject(res.data.message);
        }
    },
    (err: any) => {
        console.log(err);
        ElMessage.error("发生错误！" + err);
        console.error("发生错误！" + err);
        return Promise.reject(err);
    }
);

// 带token但无拦截器实例请求拦截器
withTokenNoIntercept.interceptors.request.use(
    (config: any) => {
        if (localStorage.user_info) {
            try {
                const userInfo: UserInfo = JSON.parse(localStorage.user_info);
                // 优先使用token字段，如果没有则使用passwordHash字段
                const token = userInfo.token || userInfo.data?.passwordHash;
                if (token && typeof token === 'string') {
                    config.headers["Authorization"] = token;
                }
            } catch (error) {
                console.error('解析用户信息失败:', error);
                localStorage.removeItem('user_info');
            }
        }
        return config;
    },
    (err: any) => {
        console.error('请求超时');
        return Promise.reject(err);
    }
);

// 带token但无拦截器实例响应拦截器
withTokenNoIntercept.interceptors.response.use(
    (res: any) => {
        if (res.data.code === 100) {
            return res.data;
        } else if (res.data.code === 102) {
            return Promise.reject("权限不足或登录已过期");
        } else {
            console.error("请求错误，服务器返回：" + res.data.message);
            return Promise.reject(res.data.message);
        }
    },
    (err: any) => {
        console.error("发生错误！" + err);
        return Promise.reject(err);
    }
);

// API实例
const api = {

    getStats() {
        return withToken.get("/stores/stats");
    },

    // 添加商家仪表盘数据获取接口
    getShopkeeperStats() {
        return withToken.get("/stores/shopkeeper-stats");
    },

    // =============== 用户认证模块 ===============
    login(user: any) {
        return instance.post("/users/login", user);
    },

    loginAdmin(user: any) {
        return instance.post("/users/loginAdmin", user);
    },

    checkMemberLevel() {
        return withToken.get("/users/checkMemberLevel");
    },

    register(user: any) {
        return instance.post("/users/register", user);
    },

    registerShopkeeper(user: any) {
        return instance.post("/users/registerShopkeeper", user);
    },

    forgotPassword(user: any) {
        return instance.post("/users/forgotPassword", user);
    },

    checkLogin() {
        return withToken.get("/users/checkLogin");
    },

    checkLoginNoIntercept() {
        return withTokenNoIntercept.get("/users/checkLogin");
    },

    logout() {
        localStorage.removeItem('user_info');
        router.push('/login');
    },

    // =============== 用户信息模块 ===============

    getUsers() {
        return withToken.get("/users/list");
    },

    getUserProfile(userId?: any) {
        // 如果传入了userId则添加到请求参数中
        if (userId) {
            return instance.get(`/users/profile?userId=${userId}`);
        }
        return withToken.get("/users/profileNoId");
    },

    updateUserProfile(userData: any) {
        // 确保userData包含userId
        return withToken.post("/users/updateprofile", userData);
    },

    uploadAvatar(formData: any) {
        // 如果formData中没有userId，尝试从本地存储中获取
        if (!formData.get('userId')) {
            try {
                const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
                const userId = userInfo.data?.userId || userInfo.data?.id || userInfo.userId || userInfo.id;
                if (userId) {
                    formData.append('userId', userId);
                }
            } catch (e) {
                console.error('解析用户信息失败:', e);
            }
        }
        return withToken.post("/users/avatar", formData);
    },

    getAvatarById(userId: any) {
        return instance.get(`/users/avatar/${userId}`);
    },

    updatePassword(passwordData: any) {
        // 确保passwordData包含userId
        return withToken.post("/users/password", passwordData);
    },

    updateUserSettings(settingsData: any) {
        // 如果settingsData中没有userId，尝试从本地存储中添加
        if (!settingsData.userId) {
            try {
                const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
                const userId = userInfo.data?.userId || userInfo.data?.id || userInfo.userId || userInfo.id;
                if (userId) {
                    settingsData.userId = userId;
                }
            } catch (e) {
                console.error('解析用户信息失败:', e);
            }
        }
        return withToken.post("/users/settings", settingsData);
    },

    // 获取用户统计数据
    getUserStats() {
        return withToken.get("/users/stats");
    },

    // 获取各类型订单数量
    getOrderCounts() {
        return withToken.get("/orders/counts");
    },

    // =============== 商店模块 ===============

    updateStore(store: any) {
        return withToken.post("/stores/update", store);
    },

    getStores(tagId: number) {
        return instance.get(`/stores/list?tagId=${tagId}`);
    },

    getStoresNoId() {
        return withToken.get("/stores/storesNoId");
    },

    getStoreDetail(storeId: number) {
        return instance.get(`/stores/store?id=${storeId}`);
    },

    getStoreServices(storeId: number) {
        return instance.get(`/stores/services?storeId=${storeId}`);
    },

    getStoreReviews(storeId: number) {
        return instance.get(`/stores/reviews?storeId=${storeId}`);
    },

    getStoreTags() {
        return instance.get("/stores/tags");
    },
    getStoreTagsById(id: any) {
        return instance.get(`/stores/getById?id=${id}`)
    },
    refreshStoreRating() {
        return instance.get("/stores/reRating");
    },
    addStore(storeInfo: any) {
        return withToken.post("/stores/addStore", storeInfo);
    },
    delStore(storeId: number) {
        return withToken.get(`/stores/delStore?storeId=${storeId}`);
    },
    getStoreList() {
        return withToken.get("/stores/getStoreList");
    },

    // =============== 商品模块 ===============

    updateProduct(product: any) {
        return withToken.post("/products/update", product);
    },

    createProduct(product: any) {
        return withToken.post("/products/create", product);
    },

    deleteProduct(productId: number) {
        return withToken.delete(`/products/delete?productId=${productId}`);
    },

    getCategories() {
        return instance.get("/categories/list");
    },

    getProductsById(productId: number) {
        return instance.get(`/products/product?productId=${productId}`);
    },

    getProductsByCategory(categoryId: number) {
        return instance.get(`/products/category?categoryId=${categoryId}`);
    },

    getProductsList() {
        return instance.get(`/products/productList`);
    },
    getProductsListByMemberLevel(){
        return withToken.get("/products/getProductsListByMemberLevel")
    },
    getOrderByPrice(categoryId: number) {
        return instance.get(`/products/orderByPrice?categoryId=${categoryId}`);
    },

    getOrderBySales(categoryId: number) {
        return instance.get(`/products/orderBySales?categoryId=${categoryId}`);
    },

    getReOrderByPrice(categoryId: number) {
        return instance.get(`/products/reOrderByPrice?categoryId=${categoryId}`);
    },

    getStoreProducts(storeId: number) {
        return instance.get(`/stores/products?storeId=${storeId}`);
    },

    getProductDetail(productId: number) {
        return instance.get(`/products/${productId}`);
    },

    searchProducts(keyword: string) {
        return instance.get(`/products/search?keyword=${keyword}`);
    },

    getProductSpecs(productId: number) {
        return instance.get(`/products/specs?productId=${productId}`);
    },

    getProductVideo(productId: number) {
        return instance.get(`/products/getProductVideo?productId=${productId}`);
    },

    // =============== 视频模块 ===============
    getVideos(params: any = {}) {
        return instance.post('/videos/list', params);
    },

    getVideosByMemberLevel() {
        return withToken.get("/videos/listByMemberLevel");
    },

    getVideosStore(storeId: number) {
        return withToken.get(`/videos/listStore?storeId=${storeId}`);
    },

    getProductsByVideoId(videoId: number) {
        return instance.get(`/products/video?videoId=${videoId}`);
    },

    getVideoDetail(videoId: number) {
        return instance.get(`/videos/video?videoId=${videoId}`);
    },

    getRecommendedVideos(videoId: number) {
        return instance.get(`/videos/recommended?videoId=${videoId}`);
    },

    likeVideo(videoId: number) {
        return withToken.post(`/videoLikes/like?videoId=${videoId}`);
    },

    likeVideoComment(commentId: number) {
        return withToken.post(`/videoComments/like?commentId=${commentId}`);
    },

    checkLike(videoId: number) {
        return withToken.get(`/videoLikes/checkLike?videoId=${videoId}`);
    },

    dislikeVideo(videoId: number) {
        return withToken.post(`/videoLikes/unlike?videoId=${videoId}`);
    },

    uploadVideo(videoData: any) {
        return withToken.post("/videos/upload", videoData);
    },

    updateVideoProducts(data: { videoId: number, productIds: number[] }) {
        return withToken.post("/videos/updateProducts", data);
    },

    updateVideo(video: any) {
        return withToken.post("/videos/update", video);
    },

    getVideoCategories() {
        return instance.get("/videos/categories");
    },

    getVideoTags() {
        return withTokenNoIntercept.get('/videos/tags');
    },

    addViewer(videoId: number) {
        return instance.get(`/videos/addViewer?videoId=${videoId}`);
    },

    getVideoComments(videoId: number) {
        return instance.get(`/videos/comments?videoId=${videoId}`);
    },

    addVideoComment(videoId: number, content: string) {
        return withToken.get(`/videoComments/addComment?videoId=${videoId}&content=${content}`);
    },

    deleteVideo(videoId: number) {
        return withToken.get(`/videos/delete?videoId=${videoId}`);
    },

    // =============== 订单模块 ===============
    createOrder(orderData: any) {
        return withToken.post("/orders/createOrder", orderData);
    },

    createBatchOrders(ordersList: any[]) {
        return withToken.post("/orders/createBatchOrders", ordersList);
    },

    getOrders(status?: string) {
        // 后端接口要求必须传递status参数，如果没有则默认为'all'
        const statusParam = status || 'all';
        return withToken.get(`/orders/getByStatus?status=${statusParam}`);
    },

    getOrderDetail(orderId: number) {
        return withToken.get(`/orders/getInfo?orderId=${orderId}`);
    },

    cancelOrder(orderId: number) {
        return withToken.get(`/orders/cancel?orderId=${orderId}`);
    },
    deleteOrder(orderId: number) {
        return withToken.delete(`/orders/delete?orderId=${orderId}`);
    },

    confirmReceipt(orderId: number) {
        return withToken.get(`/orders/confirm?orderId=${orderId}`);
    },

    getOrderLogistics(orderId: number) {
        return withToken.get(`/orders/${orderId}/logistics`);
    },

    addOrderToCart(orderId: number) {
        return withToken.post(`/orders/${orderId}/rebuy`);
    },

    // 支付订单接口
    paymentOrder(orderData: any) {
        return withToken.post("/orders/paymentOrder", orderData);
    },

    // 再次购买 - 接收商品列表
    repeatPurchase(productsList: Products[]) {
        return withToken.post(`/orders/repeatPurchase`, productsList);
    },

    // =============== 评论模块 ===============
    getProductReviews(productId: number) {
        return instance.get(`/products/${productId}/reviews`);
    },

    addProductReview(productId: number, reviewData: any) {
        return withToken.post(`/product-reviews/add`, reviewData);
    },

    // 更新订单项信息
    updateOrderItem(orderItemData: any) {
        return withToken.put('/orderItems/update', orderItemData);
    },

    // =============== 收藏模块 ===============
    getFavorites(type: string, userId?: number) {
        const url = userId
            ? `/favorites/getFavorite?type=${type}&userId=${userId}`
            : `/favorites/getFavorite?type=${type}`;
        return withToken.get(url);
    },

    addFavorite(type: string, id: number) {
        return withToken.get(`/favorites/addFavorite?type=${type}&id=${id}`);
    },

    removeFavorite(type: string, id: number) {
        return withToken.get(`/favorites/removeFavorite?type=${type}&id=${id}`);
    },

    checkFavorite(type: string, id: number) {
        return withTokenNoIntercept.get(`/favorites/checkFavorite?type=${type}&id=${id}`);
    },

    // 获取用户收藏数量
    getFavoriteCount(userId: number) {

        return withToken.get(`/favorites/getCount?userId=${userId}`);
    },

    getFavoriteNumber(type: string, id: number) {
        return instance.get(`/favorites/getFavoriteNumber?type=${type}&id=${id}`);
    },

    // =============== 支付模块 ===============
    submitPayment(paymentData: any) {
        return withToken.post("/payments", paymentData);
    },

    getPaymentMethods() {
        return instance.get("/payments/methods");
    },
    clearCart() {
        return withToken.delete("/cart");
    },
    // =============== 搜索模块 ===============
    searchByKeyword(keyword: string) {
        return instance.get(`/search/searchByKeyword?keyword=${keyword}`);
    },
    // =============== AI助手模块 ===============
    askAi(question: any) {
        return withToken.post("/ai/ask", { question });
    },

    getAiHistory() {
        return withToken.get("/ai/history");
    },
};

// 导出API方法集合
export { api };

// ！！关键修改：同时导出 backendAPI 对象！！
export { backendAPI };

// 默认导出 api 方法集合
export default api;